from flask import Flask, request, session, jsonify

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
# Dummy user data for authentication
users = {
    'user1': {'password': 'pass123', 'role': 'user'},
    'admin': {'password': 'adminpass', 'role': 'admin'}
}

@app.route('/')
def home():
    if 'username' in session:
        return f'Hello, {session["username"]}! Your role is {session["role"]}.'
    return 'Welcome to the home page. Please login.'

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if username in users and users[username]['password'] == password:
        session['username'] = username
        session['role'] = users[username]['role']
        resp = jsonify({'message': 'Login successful!'})
        resp.set_cookie('session_token', session['username'])
        return resp
    else:
        return 'Login failed. Check your username and password.'

@app.route('/logout')
def logout():
    session.pop('username', None)
    session.pop('role', None)
    resp = jsonify({'message': 'Logout successful!'})
    resp.delete_cookie('session_token')
    return resp

if __name__ == '__main__':
    app.run(debug=True)

